/*
 * KIMWONSORK@GMAIL.COM
 * COPYRIGHT CRAYONSOFT All rights reserved.
 * 2013오후 9:07:00
 * kws
 */

package com.crayon.account.fragments;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.crayon.account.dao.DAOAccount;
import com.crayon.account.dao.DAOCardBank;
import com.crayon.account.dao.DAOCategory;
import com.crayon.account.dao.DAOPhotos;
import com.crayon.account.dao.DataBaseManager;
import com.crayon.account.data.EDAType;
import com.crayon.account.data.ERuleTypes;
import com.crayon.account.impl.OnDialogFragment;
import com.crayon.sharemenu.R;
import com.crayon.util.ActivityCameraCrop;
import com.crayon.util.ActivityImageViewer;
import com.crayon.util.GDB;
import com.crayon.util.UIBIND;
import com.crayon.util.UTILCurrency;
import com.crayon.util.UTILDate;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.Where;

import net.fortuna.ical4j.model.Recur;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * com.crayon.account.fragments.FRGWrite
 * @author kws
 *
 */

//public class FragmentRGWrite extends Fragment{
//}

public class FragmentRGWrite extends Fragment
        implements View.OnClickListener
,DatePickerDialog.OnDateSetListener

,android.widget.CompoundButton.OnCheckedChangeListener
{


    public interface OnBindItemButtons{
        public List<RadioButton> OnSupportItems();
        public void OnRadioCheckedListner(RadioGroup group,int checkedId);
    }

//    //	OnBindItemButtons bindItemButtons;
//    public OnBindItemButtons getBindItemButtons() {
//        return bindItemButtons;
//    }
//
//    public void setBindItemButtons(OnBindItemButtons bindItemButtons) {
//        this.bindItemButtons = bindItemButtons;
//    }

    @Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if(getArguments()!=null){
			DAOAccount item = (DAOAccount) getArguments().getSerializable(PARAM_DAO);
			if(item!=null)setDaoAccount(item);
		}
		super.onCreate(savedInstanceState);
	}

    public static final String PARAM_DAO = "itemical";

    public static FragmentRGWrite onCreateInstance(Bundle bundle){
		FragmentRGWrite f = new FragmentRGWrite();
		f.setArguments(bundle);
		return f;
	}


	DAOAccount daoDB =null;
	DAOAccount daoAccount =new DAOAccount(EDAType.OUTCOM);
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment_item_write_out,container, false);

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		RadioGroup radoiGroupIoType = (RadioGroup)UIBIND.bindView(getView(), R.id.radoiGroupIoType);
		radoiGroupIoType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(group.getId()== R.id.radoiGroupIoType){
                    switch(checkedId){
                        case R.id.radoiIoTypeIn:getDaoAccount().setxIOType(EDAType.INCOM.getKey());break;
                        case R.id.radoiIoTypeOut:getDaoAccount().setxIOType(EDAType.OUTCOM.getKey());break;
                        case R.id.radoiIoTypefixedOut:getDaoAccount().setxIOType(EDAType.FIXEDOUTCOM.getKey());break;
                        case R.id.radoiIoTypeInfixed:getDaoAccount().setxIOType(EDAType.FIXEDINCOM.getKey());break;
                    }
                }
            }
        });
		if(getDaoAccount().getxIOType()==EDAType.INCOM.getKey()){
			radoiGroupIoType.check(R.id.radoiIoTypeIn);
		}else if(getDaoAccount().getxIOType()==EDAType.OUTCOM.getKey()){
			radoiGroupIoType.check(R.id.radoiIoTypeOut);
		}else if(getDaoAccount().getxIOType()==EDAType.FIXEDINCOM.getKey()	){
			getDaoAccount().setRecur(new Recur(Recur.MONTHLY, null).toString());
			radoiGroupIoType.check(R.id.radoiIoTypeInfixed);
		}else if(getDaoAccount().getxIOType()==EDAType.FIXEDOUTCOM.getKey()){
			getDaoAccount().setRecur(new Recur(Recur.MONTHLY,null).toString());
			radoiGroupIoType.check(R.id.radoiIoTypefixedOut);
		}


		UIBIND.bindText(getView(), R.id.topTitleName,getString(R.string.activity_title_write_household));
		UIBIND.bindButton(getView(), R.id.buttonTopRight, getString(R.string.button_text_save));

		UIBIND.bindViewVisible(getView(), R.id.topButtonBack, true);

		UIBIND.bindView(getView(), R.id.topButtonBack,this);
		UIBIND.bindView(getView(), R.id.buttonTopRight,this);
		UIBIND.bindView(getView(), R.id.buttonCategory, this);
		UIBIND.bindView(getView(), R.id.buttonCardBank,this);
		UIBIND.bindView(getView(), R.id.buttonTopModify,this);
		UIBIND.bindView(getView(), R.id.buttonDelete, this);
		UIBIND.bindView(getView(), R.id.topButtonSave, this);
		UIBIND.bindView(getView(), R.id.buttonTopCamera,this);
		UIBIND.bindView(getView(), R.id.buttonImageDelete,this);


		CheckBox checkUntil = UIBIND.bindCheckBox(getView(), R.id.checkUntil);
		checkUntil.setOnCheckedChangeListener(this);

		if(getDaoAccount()!=null && getDaoAccount().getId()>0){
			UIBIND.bindViewVisible(getView(), R.id.topButtonSave, false);
			UIBIND.bindViewVisible(getView(), R.id.buttonTopModify, true);
			UIBIND.bindViewVisible(getView(), R.id.buttonDelete, true);
		}else{
			UIBIND.bindViewVisible(getView(), R.id.topButtonSave, true);
			UIBIND.bindViewVisible(getView(), R.id.buttonTopModify, false);
			UIBIND.bindViewVisible(getView(), R.id.buttonDelete, false);

		}

		UIBIND.bindView(getView(), R.id.buttonDtStart, this);
		UIBIND.bindView(getView(), R.id.buttonRRule,this);
		UIBIND.bindView(getView(), R.id.buttonUntil,this);

		UIBIND.bindButton(getView(), R.id.buttonDtStart,UTILDate.getYYYYMDDHHMMSS(getDaoAccount().getDtStart()));
		UIBIND.bindText(getView(), R.id.textDescription,getDaoAccount().getDesciption());
		GDB.log(getClass(), "getDaoAccount().getDesciption() " + getDaoAccount().getDesciption());
		GDB.log(getClass(), "getDaoAccount().getDesciption() " + getDaoAccount().getRecur());
		if(getDaoAccount().getDtUntil()!=null){
			UIBIND.bindButton(getView(), R.id.buttonUntil,UTILDate.getYYYYMDDHHMMSS(getDaoAccount().getDtUntil()));
			UIBIND.bindCheckBoxCheck(getView(), R.id.checkUntil, true);
		}else{
			UIBIND.bindCheckBoxCheck(getView(), R.id.checkUntil, false);
		}
		if(getDaoAccount().getRecur()!=null){
			try {
				Recur recur = new Recur(getDaoAccount().getRecur());
				String frequence =recur.getFrequency();

				for(ERuleTypes types : ERuleTypes.values()){
					if(types.getRecur().equals(frequence)){
						UIBIND.bindButton(getView(), R.id.buttonRRule, getString(types.getNameId()));
						break;
					}
				}

			} catch (Exception e) {
				// TODO: handle exception
				GDB.log(getClass(), "ERR reucr " + e.getMessage());
			}
		}
		//카테고리분류.
		UIBIND.bindText(getView(), R.id.textUseCate, getDaoAccount().getxCategory());
		UIBIND.bindText(getView(), R.id.textCardBank, getDaoAccount().getXaccountName());

		//
//		mPhotoImageView = (ImageView)UIBIND.bindView(getView(), R.id.mPhotoImageView);
		UIBIND.bindView(getView(), R.id.photoImageView,this);

		if(getDaoAccount().getxImage()!=null){
			try {
				UIBIND.bindImageViewBitmapArray(getView(), R.id.photoImageView, getDaoAccount().getxImage());
				UIBIND.bindViewVisible(getView(), R.id.buttonImageDelete, true);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}


	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.buttonImageDelete:
			if(getDaoAccount()!=null && getDaoAccount().getxImage()!=null){
				getDaoAccount().setxImage(null);
				getDaoAccount().setxImageKey(null);
				UIBIND.bindViewVisible(getView(), R.id.buttonImageDelete, false);
				UIBIND.bindImageViewBitmap(getView(), R.id.photoImageView, null);
			}
			break;
		case R.id.photoImageView:
			byte[] data = getDaoAccount().getxImage();
			if(data!=null && data.length>0){
				Intent intent= new Intent(getActivity(),ActivityImageViewer.class);
				intent.putExtra(ActivityImageViewer.PARAM_IMAGE, getDaoAccount().getxImage());
				intent.putExtra(ActivityImageViewer.PARAM_URI, getDaoAccount().getxImageKey());
				startActivityForResult(intent, 0x01);
			}

			break;
		case R.id.buttonTopCamera:
			Intent intent= new Intent(getActivity(),ActivityCameraCrop.class);
			intent.putExtra(ActivityCameraCrop.PARAM_UUID, getDaoAccount().getUuid());
			startActivityForResult(intent, 0x00);
			break;
		case R.id.buttonCategory:{

			AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
			builderSingle.setIcon(R.drawable.ic_launcher);
			builderSingle.setTitle("Select One Name:-");
			final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
					getActivity(),
					android.R.layout.select_dialog_singlechoice);

			try {
				DataBaseManager dataBaseManager = DataBaseManager.getHelper(getActivity());
				Dao<DAOCategory,Integer> daocate= dataBaseManager.getDAOCategory();
				Where<DAOCategory,Integer> where = daocate.queryBuilder().where();
				RadioGroup radoiGroupIoType = (RadioGroup) UIBIND.bindView(getView(), R.id.radoiGroupIoType);
				if(radoiGroupIoType.getCheckedRadioButtonId()==R.id.radoiIoTypeIn
						|| radoiGroupIoType.getCheckedRadioButtonId()==R.id.radoiIoTypeInfixed){
					where.eq("type", DAOCategory.INCOM);
				}else if(radoiGroupIoType.getCheckedRadioButtonId()==R.id.radoiIoTypeOut
						||radoiGroupIoType.getCheckedRadioButtonId()==R.id.radoiIoTypefixedOut){
					where.eq("type", DAOCategory.OUTCOM);
				}

				for(DAOCategory category : where.query()){
					GDB.log(getClass(), "----" + category.getSummary());
					arrayAdapter.add(category.getSummary());
				}
			} catch (Exception e) {
				// TODO: handle exception
				GDB.toast(getActivity(), "FUCK err " + e.getMessage());
			}

			builderSingle.setNegativeButton("cancel",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

			builderSingle.setAdapter(arrayAdapter,
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					String strName = arrayAdapter.getItem(which);
					UIBIND.bindText(getView(), R.id.textUseCate, strName);

				}
			});
			builderSingle.show();
		}
		break;
		case R.id.buttonCardBank:{
			AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
			builderSingle.setIcon(R.drawable.ic_launcher);
			builderSingle.setTitle("Select One Name:-");
			final ArrayAdapter<String> arrayAdaptercard = new ArrayAdapter<String>(
					getActivity(),
					android.R.layout.select_dialog_singlechoice);

			try {
				DataBaseManager dataBaseManager = DataBaseManager.getHelper(getActivity());
				Dao<DAOCardBank,Integer> daocate= dataBaseManager.getDAOCardBank();
				for(DAOCardBank category : daocate.queryForAll()){
					arrayAdaptercard.add(category.getSummary());
				}
			} catch (Exception e) {
				// TODO: handle exception
				GDB.toast(getActivity(), "FUCK err " + e.getMessage());
			}

			builderSingle.setNegativeButton("cancel",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

			builderSingle.setAdapter(arrayAdaptercard,
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					String strName = arrayAdaptercard.getItem(which);
					UIBIND.bindText(getView(), R.id.textCardBank, strName);

				}
			});
			builderSingle.show();
		}
		break;
		case R.id.buttonDelete:

			if(getDaoDB().getRecur()==null){
				new AlertDialog.Builder(getActivity()).setMessage(R.string.alertmsg_write_delete_ask).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();
					}
				}).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						actionDelete();
					}
				}).create().show();

			}else{


				AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
				builderSingle.setIcon(R.drawable.ic_launcher);
				builderSingle.setTitle("Select One Name:-");
				final ArrayAdapter<String> arrayAdapterModify = new ArrayAdapter<String>(
						getActivity(),
						android.R.layout.select_dialog_singlechoice);
				final String[] itemModify=getResources().getStringArray(R.array.write_option_delete);
				for(String item: itemModify) arrayAdapterModify.add(item);
				builderSingle.setNegativeButton("cancel",
						new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

				builderSingle.setAdapter(arrayAdapterModify,
						new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String selected = arrayAdapterModify.getItem(which);
						if(selected!=null){
							try {
								if(selected.equals(getString(R.string.option_delete_all))){
									saveDeleteAll();
								}else if(selected.equals(getString(R.string.option_delete_all_afterthis))){
									saveDeleteAllAtterThis();
								}else if(selected.equals(getString(R.string.option_delete_onlythis))){
									deleteJustThis();
								}else{

								}

							} catch (Exception e) {
								// TODO: handle exception
							} finally{
								dialog.dismiss();
								getActivity().onBackPressed();
								if(getOnDialogFragment()!=null){
									getOnDialogFragment().onDismissDialog(FragmentRGWrite.this);
								}
							}
						}

					}
				});
				builderSingle.show();
			}

			break;
		case R.id.topButtonSave:
		case  R.id.buttonTopRight:

			GDB.log(getClass(), "@@ save ");
			if(!bindTextTodaoItem()){
				return;
			}

			try {
				saveModyNoRuleOne();
			} catch (Exception e) {
				// TODO: handle exception
				GDB.log(getClass(), "err save " + e.getMessage());
			} finally{

				getActivity().onBackPressed();
				if(getOnDialogFragment()!=null){
					getOnDialogFragment().onDismissDialog(this);
				}
			}

			break;
		case R.id.buttonTopModify:
			if(!bindTextTodaoItem()){
				return;
			}
			if(getDaoDB().getRecur()==null){
				try {
					saveModyNoRuleOne();

				} catch (Exception e) {
					// TODO: handle exception
				} finally{
					getActivity().onBackPressed();
					if(getOnDialogFragment()!=null){
						getOnDialogFragment().onDismissDialog(this);
					}
				}

			}else{

				//전체수정  , 이후모두 수정, 이이벤트만 수정 옵션처리.
				AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
				builderSingle.setIcon(R.drawable.ic_launcher);
				builderSingle.setTitle("Select One Name:-");
				final ArrayAdapter<String> arrayAdapterModify = new ArrayAdapter<String>(
						getActivity(),
						android.R.layout.select_dialog_singlechoice);
				final String[] itemModify=getResources().getStringArray(R.array.write_modify_option);
				for(String item: itemModify) arrayAdapterModify.add(item);
				builderSingle.setNegativeButton("cancel",
						new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

				builderSingle.setAdapter(arrayAdapterModify,
						new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						String selected = arrayAdapterModify.getItem(which);
						if(selected!=null){
							try {
								if(selected.equals(getString(R.string.option_modify_all))){
									saveModifyAll();
								}else if(selected.equals(getString(R.string.option_modify_all_afterthis))){
									saveModifyAllAtterThis();
								}else if(selected.equals(getString(R.string.option_modify_onlythis))){
									saveModifyJustThis();
								}else{

								}

							} catch (Exception e) {
								// TODO: handle exception
							} finally{
								dialog.dismiss();
								getActivity().onBackPressed();
								if(getOnDialogFragment()!=null){
									getOnDialogFragment().onDismissDialog(FragmentRGWrite.this);
								}
							}
						}

					}
				});
				builderSingle.show();
			}

			break;
		case R.id.topButtonBack:
			getActivity().onBackPressed();
			if(getOnDialogFragment()!=null){
				getOnDialogFragment().onDismissDialog(FragmentRGWrite.this);
			}

			break;
		case  R.id.buttonDtStart:
			DatePickerDialog td = new DatePickerDialog(getActivity()
					,this
					,UTILDate.getYear(daoAccount.getDtStart())
					,UTILDate.getMonth(daoAccount.getDtStart())
					,UTILDate.getDAYIntValue(daoAccount.getDtStart())
					);
			td.getDatePicker().setId(R.id.buttonDtStart);
			td.show();

			break;
		case R.id.buttonUntil:
			DatePickerDialog tdUntil = new DatePickerDialog(getActivity()
					,this
					,UTILDate.getYear(daoAccount.getDtStart())
					,UTILDate.getMonth(daoAccount.getDtStart())
					,UTILDate.getDAYIntValue(daoAccount.getDtStart())
					);
			tdUntil.getDatePicker().setId(R.id.buttonUntil);

			tdUntil.show();
			break;
		case R.id.buttonRRule:

			AlertDialog.Builder builderRule = new AlertDialog.Builder(getActivity());
			builderRule.setIcon(R.drawable.ic_launcher);
			builderRule.setTitle("Select One Name:-");
			final ArrayAdapter<String> arrayAdapterModify = new ArrayAdapter<String>(
					getActivity(),
					android.R.layout.select_dialog_singlechoice);
			final String[] itemModify=getResources().getStringArray(R.array.write_option_frequences);
			for(String item: itemModify) arrayAdapterModify.add(item);
			builderRule.setNegativeButton("cancel",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

			builderRule.setAdapter(arrayAdapterModify,
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					String selected = arrayAdapterModify.getItem(which);
					if(selected!=null){
						try {
							UIBIND.bindButton(getView(), R.id.buttonRRule, selected);
							Recur recur = new Recur(Recur.DAILY);
							if(selected.equals(getString(R.string.option_frequence_daily))){
								recur.setFrequency(Recur.DAILY);
							}else if(selected.equals(getString(R.string.option_frequence_weekly))){
								recur.setFrequency(Recur.WEEKLY);

							}else if(selected.equals(getString(R.string.option_frequence_monthly))){
								recur.setFrequency(Recur.MONTHLY);


							}else if(selected.equals(getString(R.string.option_frequence_yearly))){
								recur.setFrequency(Recur.YEARLY);

							}else{
								recur=null;
							}
							getDaoAccount().setRecur(recur!=null ? recur.toString():null);


						} catch (Exception e) {
							// TODO: handle exception
						} finally{
						}
					}

				}
			});
			builderRule.show();
			//			FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
			//			FragmentPoplist prev = (FragmentPoplist)getActivity().getSupportFragmentManager().findFragmentByTag(FragmentPoplist.class.getSimpleName());
			//			if (prev != null) {
			//				ft.remove(prev);
			//			}
			//			ft.addToBackStack(null);
			//			FragmentPoplist f= new FragmentPoplist();
			//			f.setBindItemButtons(this);
			//			f.show(ft, FragmentPoplist.class.getSimpleName());

			break;
		}
	}


	private void setUntilDateWithRule(){
		if(getDaoAccount().getRecur()!=null){
			try {
				Recur recur =new Recur(getDaoAccount().getRecur());
				GDB.log(getClass(), " 반복설정 UNTIL" + recur.toString());
				if(getDaoAccount().getDtUntil()!=null){
					GDB.log(getClass(), " 반복설정 UNTIL" + UTILDate.getYYYYMMDD(getDaoAccount().getDtUntil()));
					recur.setUntil(UTILDate.getConvertICal4jDate(getDaoAccount().getDtUntil()));
				}else{
					recur.setUntil(null);
				}
				getDaoAccount().setRecur(recur.toString());
			} catch (Exception e) {
				// TODO: handle exception
				GDB.log(getClass(), "ERR " + e.getMessage());
			}
		}
		UIBIND.bindButton(getView(), R.id.buttonUntil, UTILDate.getYYYYMMDD(getDaoAccount().getDtUntil()));

	}
	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		// TODO Auto-generated method stub
		switch(view.getId()){
		case R.id.buttonUntil:
			getDaoAccount().setDtUntil(UTILDate.setYYYYMMDD(getDaoAccount().getDtStart(), year, monthOfYear, dayOfMonth));
			setUntilDateWithRule();
			break;
		case R.id.buttonDtStart:
			getDaoAccount().setDtStart(UTILDate.setYYYYMMDD(getDaoAccount().getDtStart(), year, monthOfYear, dayOfMonth));
			getDaoAccount().setDtEnd(UTILDate.setYYYYMMDD(getDaoAccount().getDtStart(), year, monthOfYear, dayOfMonth));
			UIBIND.bindButton(getView(), R.id.buttonDtStart,UTILDate.getYYYYMDDHHMMSS(getDaoAccount().getDtStart()));

			break;
		}
	}

//	@Override
//	public List<RadioButton> OnSupportItems() {
//		// TODO Auto-generated method stub
//		LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);;
//		List<RadioButton> items =new ArrayList<RadioButton>();
//		for(ERuleTypes types : ERuleTypes.values()){
//			RadioButton button = (RadioButton)inflater.inflate(R.layout.radiobutton_item, null);
//			button.setId(types.getKey());
//			button.setText(getString(types.getNameId()));
//			items.add(button);
//		}
//		return items;
//
//	}

//	@Override
//	public void OnRadioCheckedListner(RadioGroup group, int checkedId) {
//		// TODO Auto-generated method stub
//		for(ERuleTypes types : ERuleTypes.values()){
//			if(types.getKey()==checkedId){
//				GDB.log(getClass(), "반복프리퀜시 설정하기 선택" + types.getRecur());
//				UIBIND.bindButton(getView(), R.id.buttonRRule, getString(types.getNameId()));
//				try {
//					Recur recur = new Recur(Recur.DAILY);
//					recur.setFrequency(types.getRecur());
//					GDB.log(getClass(), "반복프리퀜시 설정하기 값" + recur.toString());
//					getDaoAccount().setRecur(recur.toString());
//
//				} catch (Exception e) {
//					// TODO: handle exception
//					GDB.log(getClass(), "ERR 프리퀜시 설정" + e.getMessage());
//				}
//				break;
//			}
//		}
//
//		//		TextSwitcher switcher =new TextSwitcher(getActivity());
//
//	}



	public DAOAccount getDaoAccount() {
		return daoAccount;
	}

	public void setDaoAccount(DAOAccount daoAccount) {
		this.daoAccount = daoAccount;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();


		if(getDaoAccount()!=null && getArguments()!=null){

			RadioGroup radoiGroupIoType = (RadioGroup)UIBIND.bindView(getView(), R.id.radoiGroupIoType);
			if(getDaoAccount().getId()>0){
				DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
				try {
					setDaoDB(baseManager.getDAOAccount().queryForId(getDaoAccount().getId()));
				} catch (Exception e) {
					// TODO: handle exception
				}
				radoiGroupIoType.setVisibility(View.GONE);

			}
			GDB.log(getClass(), "summary " + getDaoAccount().getSummary());
			GDB.log(getClass(), "price " + getDaoAccount().getXprice());

			UIBIND.bindText(getView(), R.id.textSummary, getDaoAccount().getSummary());
			if(getDaoAccount().getXprice()>0)
				UIBIND.bindText(getView(), R.id.textPrice, UTILCurrency.formatPrice(getDaoAccount().getXprice()));
			UIBIND.bindText(getView(), R.id.buttonDtStart, UTILDate.getYYYYMMDD(getDaoAccount().getDtStart()));
		}


//		if(getDaoAccount()!=null && getDaoAccount().getUuid()!=null){
//			DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
//			try {
//				Where<DAOPhotos,Integer> where = baseManager.getDAOPhotos().queryBuilder().where();
//				where.eq("uuid", getDaoAccount().getUuid());
//				List<DAOPhotos> photos = where.query();
//				if(photos!=null &&photos.size()>0){
//					for(DAOPhotos item : photos){
//						byte[] bitmaps = item.getArrays();
//						Bitmap bitmap = BitmapFactory.decodeByteArray(bitmaps,0,bitmaps.length);
//						getDaoAccount().setxImage(Arrays.copyOf(bitmaps, bitmaps.length));
//						UIBIND.bindImageViewBitmap(getView(), R.id.photoImageView, bitmap);
//						break;
//					}
//				}
//			} catch (Exception e) {
//				// TODO: handle exception
//			}
//
//			//photoImageView
//		}
	}

	private void actionDelete(){
		try {
			DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
			dao.delete(getDaoAccount());
		}catch (Exception e) {
			// TODO: handle exception
		}finally{
			getActivity().onBackPressed();
			if(getOnDialogFragment()!=null){
				getOnDialogFragment().onDismissDialog(this);

			}

		}
	}

	public DAOAccount getDaoDB() {
		return daoDB;
	}

	public void setDaoDB(DAOAccount daoDB) {
		this.daoDB = daoDB;
	}

	private boolean bindTextTodaoItem(){
		getDaoAccount().setSummary(UIBIND.getTextValue(getView(), R.id.textSummary));
		getDaoAccount().setXprice(UIBIND.getTextValueNumber(getView(), R.id.textPrice));
		getDaoAccount().setDesciption(UIBIND.getTextValue(getView(), R.id.textDescription));
		getDaoAccount().setxCategory(UIBIND.getTextValue(getView(), R.id.textUseCate));
		getDaoAccount().setXaccountName(UIBIND.getTextValue(getView(), R.id.textCardBank));

		if(getDaoAccount().getSummary()==null){
			Toast.makeText(getActivity(), getString(R.string.toast_message_need_title), Toast.LENGTH_SHORT).show();
			return false;
		}
		if(getDaoAccount().getXprice()==0){
			Toast.makeText(getActivity(),getString(R.string.toast_message_need_price) , Toast.LENGTH_SHORT).show();
			return false;
		}


		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		//카테고리 추가.
		try {
			if(getDaoAccount().getxCategory()!=null){
				Dao<DAOCategory,Integer> daoCate = baseManager.getDAOCategory();
				RadioGroup radoiGroupIoType = (RadioGroup)UIBIND.bindView(getView(), R.id.radoiGroupIoType);
				if(radoiGroupIoType.getCheckedRadioButtonId()==R.id.radoiIoTypeIn){
					daoCate.createIfNotExists(new DAOCategory(DAOCategory.INCOM,getDaoAccount().getxCategory()));
				}else if(radoiGroupIoType.getCheckedRadioButtonId()==R.id.radoiIoTypeOut){
					daoCate.createIfNotExists(new DAOCategory(DAOCategory.OUTCOM,getDaoAccount().getxCategory()));
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return true;
	}

	private void saveModyNoRuleOne() throws Exception{
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
			if(getDaoAccount().getId()>0){
				dao.update(getDaoAccount());
			}else{
				dao.create(getDaoAccount());
			}
			List<DAOAccount> list = dao.queryForAll();
			for(DAOAccount item : list){
				GDB.log(getClass(), "item " + item.getSummary() +"\t" + item.getXprice() +"\t" + UTILDate.getYYYYMMDD(item.getDtStart()));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	//UUID가 똑 같은 모든 것을 수정한다.
	private void saveModifyAll() throws Exception{
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());

			dao.update(getDaoAccount());

			//			UpdateBuilder<DAOAccount,Integer> builder = dao.updateBuilder();
			//			Where<DAOAccount,Integer> where = builder.where();
			//			where.eq("uuid", getDaoAccount().getUuid());
			//			builder.updateColumnValue("dtStart", getDaoAccount().getDtStart());
			//			builder.updateColumnValue("dtEnd", getDaoAccount().getDtStart());
			//			builder.updateColumnValue("summary", getDaoAccount().getSummary());
			//			builder.updateColumnValue("xprice", getDaoAccount().getXprice());
			//			builder.updateColumnValue("xCategory", getDaoAccount().getxCategory());
			//			builder.updateColumnValue("xaccountName", getDaoAccount().getXaccountName());
			//			builder.updateColumnValue("recur", getDaoAccount().getRecur());
			//			builder.updateColumnValue("dtUntil", getDaoAccount().getUn);
			//			builder.setWhere(where);
			//			builder.update();

		} catch (Exception e) {
			// TODO: handle exception
			GDB.log(getClass(), "err 전체 수정 " + e.getMessage());
		}
	}

	//이후 모든것을 변경한다.
	//원천것을 시작일까지 업데이트 한다.
	//시작일 이후 새로운 이벤트를 생성한다.
	private void saveModifyAllAtterThis() throws Exception{
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			//오리지널 데이타를 가져와 untils을 세팅한다.
			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
			if(getDaoDB().getId()>0){
				if(getDaoDB().getRecur()!=null){
					getDaoDB().setDtUntil(getDaoAccount().getDtStart());
					Recur recur = new Recur(getDaoDB().getRecur());
					recur.setUntil(UTILDate.getConvertICal4jDate(getDaoAccount().getDtStart()));//시작일을 부모의 종료일로 설정한다.
					getDaoDB().setRecur(recur.toString());
					GDB.log(getClass(),"이후 이전 것 반복 언틀세팅 " + recur.toString());
				}
				dao.update(getDaoDB());
			}
			{
				//
				GDB.log(getClass(),"이후 모든것 새로운 이벤트 생성");
				getDaoAccount().setId(0);
				getDaoAccount().setUuid(getDaoDB().getUuid());
				dao.create(getDaoAccount());
			}

		} catch (Exception e) {
			// TODO: handle exception
			GDB.log(getClass(), "이후 모든 것 변경에 대한 처리 오류 발생" + e.getMessage());

		}
	}

	/**
	 * 이것만 수정한다.
	 * 1. 제외일을 넣는다.
	 *
	 * @throws Exception
	 */
	private void saveModifyJustThis() throws Exception{
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			//오리지널 데이타를 가져와 untils을 세팅한다.
			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
			if(getDaoDB().getId()>0){
				getDaoDB().addSaveExDate(getDaoAccount().getDtStart());
				dao.update(getDaoDB());
			}
			{

				getDaoAccount().setId(0);
				getDaoAccount().setUuid(getDaoDB().getUuid());
				getDaoAccount().setRecur(null);
				dao.create(getDaoAccount());
			}
			List<DAOAccount> list = dao.queryForAll();
			for(DAOAccount item : list){
				GDB.log(getClass(), "item " + item.getSummary() +"\t" + item.getXprice() +"\t" + UTILDate.getYYYYMMDD(item.getDtStart()));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	private void deleteJustThis() throws Exception{
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			//오리지널 데이타를 가져와 untils을 세팅한다.
			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
			if(getDaoDB().getId()>0){
				getDaoDB().addSaveExDate(getDaoAccount().getDtStart());
				dao.update(getDaoDB());
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}


	private void saveDeleteAll() throws Exception{
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
			DeleteBuilder<DAOAccount,Integer> builder = dao.deleteBuilder();
			Where<DAOAccount,Integer> where = builder.where();
			where.eq("uuid", getDaoAccount().getUuid());
			builder.setWhere(where);
			builder.delete();
		} catch (Exception e) {
			// TODO: handle exception
			GDB.log(getClass(), "err 전체 수정 " + e.getMessage());
		}
	}

	private void saveDeleteAllAtterThis() throws Exception{
		DataBaseManager baseManager = DataBaseManager.getHelper(getActivity());
		try {
			//오리지널 데이타를 가져와 untils을 세팅한다.
			Dao<DAOAccount, Integer> dao =  baseManager.getDAOAccount();
			GDB.log(getClass(), "getDaoAccount().getId() " + getDaoAccount().getId());
			if(getDaoDB().getId()>0){
				if(getDaoDB().getRecur()!=null){
					getDaoDB().setDtUntil(getDaoAccount().getDtStart());
					Recur recur = new Recur(getDaoDB().getRecur());
					recur.setUntil(UTILDate.getConvertICal4jDate(getDaoAccount().getDtStart()));//시작일을 부모의 종료일로 설정한다.
					getDaoDB().setRecur(recur.toString());
					GDB.log(getClass(),"이후 이전 것 반복 언틀세팅 " + recur.toString());
				}
				dao.update(getDaoDB());
			}


		} catch (Exception e) {
			// TODO: handle exception
			GDB.log(getClass(), "이후 모든 것 변경에 대한 처리 오류 발생" + e.getMessage());

		}
	}
	OnDialogFragment onDialogFragment;
	public OnDialogFragment getOnDialogFragment() {
		return onDialogFragment;
	}

	public void setOnDialogFragment(OnDialogFragment onDialogFragment) {
		this.onDialogFragment = onDialogFragment;
	}

//	@Override
//	public void onCheckedChanged(RadioGroup group, int checkedId) {
//		// TODO Auto-generated method stub
//		if(group.getId()== R.id.radoiGroupIoType){
//			switch(checkedId){
//			case R.id.radoiIoTypeIn:getDaoAccount().setxIOType(EDAType.INCOM.getKey());break;
//			case R.id.radoiIoTypeOut:getDaoAccount().setxIOType(EDAType.OUTCOM.getKey());break;
//			case R.id.radoiIoTypefixedOut:getDaoAccount().setxIOType(EDAType.FIXEDOUTCOM.getKey());break;
//			case R.id.radoiIoTypeInfixed:getDaoAccount().setxIOType(EDAType.FIXEDINCOM.getKey());break;
//			}
//		}
//	}
//
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		// TODO Auto-generated method stub
		if(buttonView.getId()==R.id.checkUntil){
			if(isChecked==false){
				UIBIND.bindButton(getView(), R.id.buttonUntil, "");
				getDaoAccount().setDtUntil(null);
				setUntilDateWithRule();
			}
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		GDB.log(getClass(), ">>>>onActivityResult REQUESTCODE_CAMERA " + ActivityCameraCrop.REQUESTCODE_CAMERA);
		GDB.log(getClass(), ">>>>onActivityResult " + requestCode);
		GDB.log(getClass(), ">>>>onActivityResult " + resultCode);
		GDB.log(getClass(), ">>>>onActivityResult " + data);

		if(data!=null){
			byte[] imgarr = data.getByteArrayExtra("data");
			if(imgarr!=null &&imgarr.length>0){
				getDaoAccount().setxImage(Arrays.copyOf(imgarr, imgarr.length));
				try {
					UIBIND.bindImageViewBitmapArray(getView(), R.id.photoImageView, getDaoAccount().getxImage());
					UIBIND.bindViewVisible(getView(), R.id.buttonImageDelete, true);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			DAOPhotos daophoto = (DAOPhotos)data.getSerializableExtra("daophoto");
			getDaoAccount().setxImageKey(daophoto.getUri());
		}

		super.onActivityResult(requestCode, resultCode, data);


	}
}